package sevencm.wechat.common;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class BeanRegister {

  private final ConfigurableApplicationContext applicationContext;
 
  public BeanRegister(ConfigurableApplicationContext applicationContext) {
    this.applicationContext = applicationContext;
  }

  /**
   * 动态注册bean
   * @param name
   * @param clazz
   * @param args
   * @param <T>
   * @return
   */
  public <T> T registerBean(String name, Class<T> clazz, Object... args) {
    BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
    if (args.length > 0) {
      for (Object arg : args) {
        beanDefinitionBuilder.addConstructorArgValue(arg);
      }
    }
    BeanDefinition beanDefinition = beanDefinitionBuilder.getRawBeanDefinition();
    BeanDefinitionRegistry beanFactory = (BeanDefinitionRegistry) applicationContext.getBeanFactory();
    beanFactory.registerBeanDefinition(name, beanDefinition);
    return applicationContext.getBean(name, clazz);
  }
}